package utils;



/*
    JDBC工具类: 用来获取连接对象,释放资源

    练习:
        用配置文件
 */
/*public class JDBCUtil {
    //定义数据库的连接地址
    private static String url = "jdbc:mysql://localhost:3306/day18";
    //定义用户名
    private static String userName = "root";
    //定义密码
    private static String passWord = "root";
    //定义驱动全类名
    private static String driverClassName = "com.mysql.jdbc.Driver";
    //构造私有
    private JDBCUtil(){}

    //注册驱动,只需要一次,放到静态代码块中
    //优先于非静态代码块执行，只执行一次
    static {
        //1.注册驱动
        try {
            Class.forName(driverClassName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //定义静态方法,获取Connection连接对象
    public static Connection getConnection() throws Exception {
        //2. 获得连接.
        //调用方法,获取到数据库的连接对象
        Connection con = DriverManager.getConnection(url, userName, passWord);
        return con;
    }

    //释放资源
    public static void release(Connection con, Statement stmt, ResultSet rs) {
        //4.关闭资源
        if(con!=null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stmt!=null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(rs!=null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}*/


import java.sql.*;

public class JDBCUtil {
    public JDBCUtil() {
    }
   private  static String url ="jdbc:mysql://localhost:3306/day18";
    private static String userName = "root";
    private static String password="root";
    private static String classname="com.mysql.jdbc.Driver";
//只执行一次
    static {
        try{
            Class.forName(classname);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //静态方法存在于公共内存空间，不必创建对象调用
    //Connection为抽象公共类，getConnection为这个抽象类的实现类，返回实现类对象
    public static Connection getConnection() throws SQLException {
        Connection connection= DriverManager.getConnection(url, userName, password);
        return  connection;
    }

    public static void release(Connection connection, Statement statement, ResultSet resultSet){
        if (connection !=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (statement!=null){
            try {
               statement.close();
            }catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}